package denaris.midlet;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import denaris.core.entity.Player;

/**
 * The main midlet class that handles the screens. It also takes care of all
 * commands.
 * 
 * @author stkl23
 * 
 */
public class Denaris extends MIDlet implements CommandListener {
	private static Denaris instance;

	private Command cmdExit;
	
	DenarisGameCanvas canvas;
	
	public Denaris() {
		// do not use lazy initialization in the getInstance-method
		if (instance == null) {
			instance = this;
		}
	}

	protected void destroyApp(boolean unconditional)
			throws MIDletStateChangeException {
		// stop all screens (in case they're still running)
		DenarisGameCanvas.getInstance().stop();
		notifyDestroyed();
	}

	protected void pauseApp() {

	}

	protected void startApp() throws MIDletStateChangeException {
		// create the game canvas
		canvas = DenarisGameCanvas.getInstance();
		canvas.setCommandListener(this);
		// add an exit command
		cmdExit = new Command("Exit", Command.EXIT, 1);
		canvas.addCommand(cmdExit);
		// set the game screen visibile and start its thread
		canvas.showScreen(GameScreen.getInstance());
		canvas.show();
	}

	public void commandAction(Command c, Displayable d) {
		if (c == cmdExit) {
			onDestruction();
		}
	}

	public void onDestruction() {
		try {
			destroyApp(true);
		} catch (MIDletStateChangeException e) {
			handleException(e);
		}
	}

	public void handleException(Exception e) {
		e.printStackTrace();
		Display.getDisplay(this).setCurrent(new Alert(e.getMessage()), null);
	}

	public static Denaris getInstance() {
		return instance;
	}

	public void notifyPlayerDied() {
		canvas.showScreen(GameFadeScreen.getInstance());
	}

	public void notifyFaded() {
		Player player = GameScreen.getInstance().getPlayer();
		// subtract one life from the player
		player.decLifeCount();
		// do we have more lives to spend?
		if (player.getLifeCount() >= 0) {
			canvas.showScreen(GetReadyScreen.getInstance());
		}else {
			// noo.. game over!
			canvas.showScreen(GameOverScreen.getInstance());
		}
		
	}

	public void notifyReady() {
		canvas.showScreen(GameScreen.getInstance());
	}
	
	public void notifyGameOver() {
		// we would normaly show the menu screen now...
	}
}
